﻿package
{	
	import flash.net.URLLoader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	import flash.system.Security;

	public class GameSettings extends EventDispatcher
	{	
		public const DATA_LOADED:String = 'DATA_LOADED';
		
		private var FSettingsURL:String;
		//Common settings
		private var FScriptsDirectory:String;
		private var FVKAutorization:String;
		private var FVKRequest:String;
		private var FHost:String;
		private var FPort:int;
		private var FClientURL:String;
		//Game specific data
		private var FDefaultSkin:int;
		//XML loader
		private var FLoader:URLLoader;
		
		public function GameSettings(AURL:String):void
		{
			FClientURL = new String();
			FHost = new String();
			FScriptsDirectory = new String();
			FPort = -1;
			
			FSettingsURL = AURL;			
			FLoader = new URLLoader();
			FLoader.addEventListener(Event.COMPLETE, OnSettingsLoaded);
		}
		
		public function Load():void
		{
			FLoader.load(new URLRequest(FSettingsURL));
		}
		
		private function OnSettingsLoaded(e:Event):void
		{
			var vXML:XML = XML(e.target.data);
			
			FClientURL = vXML.Client.@URL;
			FScriptsDirectory = vXML.Scripts.@ScriptsDirectory;			
			FHost = vXML.Multiplayer.@Host;
			FPort = vXML.Multiplayer.@Port;
			FVKAutorization = vXML.VK.@Autorization;
			FVKRequest = vXML.VK.@Requests;
			//Game specific data
			FDefaultSkin = vXML.Special.@DefaultSkin;
			
			UpdateSecurity(FClientURL);
			
			dispatchEvent(new Event(DATA_LOADED));
		}
		
		private function UpdateSecurity(APath:String)
		{
			var s:String = APath.substr(7, APath.length);			
			var Trims:Array = s.split('.');
			s = Trims[0];
			Security.loadPolicyFile("http://" + s + ".vkontakte.ru/crossdomain.xml");
			Security.loadPolicyFile("http://" + s + ".vk.com/crossdomain.xml");
		}
		
		public function get ClientURL():String
		{
			return FClientURL;
		}
		
		public function get Host():String
		{
			return FHost;
		}
		
		public function get Port():int
		{
			return FPort;
		}
		
		private function get PolicyPort():int
		{
			return FPort + 1;
		}
		
		public function get PolicyServer():String
		{
			return "xmlsocket://" + Host + ":" + PolicyPort;
		}
		
		public function get ScriptsDirectory():String
		{
			return FScriptsDirectory;
		}
		
		public function get VKAutorization():String
		{
			return FScriptsDirectory + FVKAutorization;
		}
		
		public function get VKRequest():String
		{
			return FScriptsDirectory + FVKRequest;
		}
		
		// ================================================== GameSpecific ======================================================== //
		
		public function get DefaultSkin():int
		{
			return FDefaultSkin;
		}
	}	
}
